package com.ruoyi.web.a2.service.impl;


import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.ruoyi.common.config.DbInterfaceConfig;
import com.ruoyi.common.enums.FlightPathTypeEnum;
import com.ruoyi.common.utils.Date2Utils;
import com.ruoyi.common.utils.IdentitiesUtils;
import com.ruoyi.common.utils.a2.TrajectoryPoint;
import com.ruoyi.common.utils.a2.TrajectoryPredictorUtils;
import com.ruoyi.common.utils.crudinterface.CrudInterfaceUtils;
import com.ruoyi.common.utils.crudinterface.vo.ReqVo;
import com.ruoyi.common.utils.geotools.GeoCalculatorUtils;
import com.ruoyi.web.a2.domain.JKySMbdxycytyp;
import com.ruoyi.web.a2.domain.JKySMbjbxx;
import com.ruoyi.web.a2.dto.A2TmpAndIaJson;
import com.ruoyi.web.a2.service.ITool2aHandleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Slf4j
@Service
public class Tool2aHandleImpl implements ITool2aHandleService {

    @Autowired
    private DbInterfaceConfig dbInterfaceConfig;

    @Override
    public List<JKySMbdxycytyp> a2TmpAndIa(A2TmpAndIaJson json) {
        List<JKySMbdxycytyp> a2TmpAndIaList = Lists.newArrayList();

        FlightPathTypeEnum flightPathTypeEnum = FlightPathTypeEnum.getByCode(json.getType());
        //动态组装sql，查询AIS/ADS-B动态信息表
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ")
                .append("jd AS lon,wd AS lat,hs AS speed,hx AS way,jzsj AS \"timestamp\"")
                .append(" FROM ")
                .append(flightPathTypeEnum.getDynamicsTableName())
                .append(" WHERE jd IS NOT NULL AND wd IS NOT NULL AND ")
                .append(flightPathTypeEnum.getMmsiIcao()).append(" ='").append(json.getTargetNum()).append("'")
                .append(" AND jzsj >='").append(json.getStartTime()).append("'")
                .append(" AND jzsj <='").append(json.getEndTime()).append("'")
                .append(" ORDER BY jzsj");
        CrudInterfaceUtils crudInterfaceUtils = new CrudInterfaceUtils();
        Object dbList = crudInterfaceUtils.getList(dbInterfaceConfig, new ReqVo(sql.toString()), TrajectoryPoint.class);
        List<TrajectoryPoint> list = (List<TrajectoryPoint>) dbList;
        if (!CollectionUtils.isEmpty(list)) {
            List<List<TrajectoryPoint>> resultList = Lists.newArrayList();
            int resultSize = 3;
            for (int i = 0; i <resultSize ; i++) {
                //调用航迹预测算法
                resultList.add(TrajectoryPredictorUtils.predictTrajectory(list));
            }

            String oldFlightPath = JSON.toJSONString(list);
            int[] probabilityArr = IdentitiesUtils.generateRandomNumbers();

            //入库【目标动向预测和意图研判表 j_ky_s_mbdxycytyp】
            for (int i = 0; i < resultSize; i++) {
                List<TrajectoryPoint> trackPointList = resultList.get(i);
                String newFlightPath = JSON.toJSONString(trackPointList);
                TrajectoryPoint lastTrackPoint = trackPointList.get(trackPointList.size() - 1);
                log.info("lastTrackPoint={}",lastTrackPoint.toString());

                JKySMbdxycytyp a2TmpAndIa = new JKySMbdxycytyp();
                a2TmpAndIa.setMmsiicao(json.getTargetNum());
                a2TmpAndIa.setLshjsj(oldFlightPath);
                a2TmpAndIa.setWlhjsj(newFlightPath);
                a2TmpAndIa.setYcddzdsj(Date2Utils.timestampToDateTimeStr(lastTrackPoint.getTimestamp()));

                JKySMbjbxx targetBaseInfo = getTargetInfo(lastTrackPoint);
                if (targetBaseInfo != null) {
                    a2TmpAndIa.setYcddzdmbid(targetBaseInfo.getId());
                    a2TmpAndIa.setYcddzdmbmc(targetBaseInfo.getMbmc());
                }
                a2TmpAndIa.setGl(Double.valueOf(probabilityArr[i]));
                a2TmpAndIaList.add(a2TmpAndIa);

                String insertSqlTemplate = "insert into j_ky_s_mbdxycytyp(mmsiicao, lshjsj, wlhjsj, ycddzdsj, ycddzdmbid, gl) values ('%s','%s','%s','%s',%d,%f)";
                String insertSql = String.format(insertSqlTemplate,a2TmpAndIa.getMmsiicao(),a2TmpAndIa.getLshjsj(),a2TmpAndIa.getWlhjsj(),a2TmpAndIa.getYcddzdsj(),a2TmpAndIa.getYcddzdmbid(),a2TmpAndIa.getGl());
                crudInterfaceUtils.create(dbInterfaceConfig,new ReqVo(insertSql));
            }

        }
        return a2TmpAndIaList;
    }

    /**
     * 1、查询目标基本信息表（经度、纬度都不为空的数据）.
     * 2、用当前点位与每个目标点位进行距离比较，最近的目标点位就是返回值.,
     *
     * @param lastTrackPoint the last track point
     * @return the target info
     * @author :yanlixiong
     * @date :2025-02-21 17:05:48
     */
    private JKySMbjbxx getTargetInfo(TrajectoryPoint lastTrackPoint) {
        String sql = "SELECT id,mbmc,jd,wd FROM j_ky_s_mbjbxx WHERE jd IS NOT NULL AND wd IS NOT NULL";
        CrudInterfaceUtils crudInterfaceUtils = new CrudInterfaceUtils();
        Object dbList = crudInterfaceUtils.getList(dbInterfaceConfig, new ReqVo(sql), JKySMbjbxx.class);
        List<JKySMbjbxx> list = (List<JKySMbjbxx>) dbList;
        if (!CollectionUtils.isEmpty(list)) {
            double distanceResult = -1;
            JKySMbjbxx targetBaseInfoResult = null;
            for (JKySMbjbxx targetBaseInfo:list) {
                double distance = GeoCalculatorUtils.getDistance(lastTrackPoint.getLon(), lastTrackPoint.getLat(), targetBaseInfo.getJd(), targetBaseInfo.getWd());
                if(distanceResult==-1 || distance < distanceResult){
                    distanceResult = distance;
                    targetBaseInfoResult = targetBaseInfo;
                }
            }
            return targetBaseInfoResult;
        }
        return null;
    }
}
